package com.osce.common.core.redis;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.doudou.core.random.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author zzxjs
 * @since 2023/9/4
 * 使用redis setnx机制定义加锁机制
 */
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisLock {
    private static final Log log = LogFactory.get(RedisLock.class);

    @Autowired
    public RedisTemplate redisTemplate;

    private long tiemout() {//默认超时时间为一分钟
        return 60;
    }

    public boolean lock(String key) {
        return lock(key, tiemout());
    }

    public boolean lock(String key, long timeout) {
        try {
            return redisTemplate.opsForValue().setIfAbsent(key, UUIDUtil.uuid(), timeout, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("redis lock error", e);
            return false;
        }
    }

    public boolean unLock(String key) {
        try {
            return redisTemplate.delete(key);
        } catch (Exception e) {
            log.error("redis unlock error", e);
            return false;
        }
    }

}
